<p>
    <a href="<%= pageUrl %>detail" target="_blank">添加书籍</a>
</p>
<input id="searchInput" type="text" />
<input id="searchButton" type="button" value="搜索" />
<!-- 搜索书籍 -->
<script>
    var requestParams = getParams();
    var searchbox = document.getElementById("searchInput");
    var keyword = (requestParams["keyword"] || "").trim();
    search({
        tableElementId: "book-table",
        searchText: null,
        categoryId: null
    });

    $("#searchButton").click(function () {
        search({
            tableElementId: "book-table",
            searchText: $("#searchInput").val(),
            categoryId: null
        });
    });

    function search({ tableElementId = "", searchText = "", categoryId = 0 }) {
        getRequest("/book/search", { bookName: searchText, categoryId: categoryId })
            .then(function (responseData) {
                var axiosData = responseData.data;
                var status = axiosData.status;
                var data = axiosData.data;
                if (status === "success") {
                    // console.log(data)

                    // 数据进行转换
                    var renderData = [];
                    data.forEach(element => {
                        var mainDivWidth = 96/*vw*/; // 定义div的宽度（用于计算表格中的数据的显示长度）
                        var columnWidth = [20, 15, 10, 15, 5, 35];
                        renderData.push({
                            编号: `${element.id}`,
                            书名: `<a target="_blank" href="/book?id=${element.id}">
                                        <span class="overflow-omit" style="max-width: ${columnWidth[0] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                            ${element.bookName}
                                        </span>
                                    </a>`,
                            分类: `<a target="_blank" href="/category?id=${element.category.id}">
                                        <span class="overflow-omit" style="max-width: ${columnWidth[1] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                            ${element.category.name}
                                        </span>
                                    </a>`,
                            作者: `<span class="overflow-omit" style="max-width: 300px; max-height: 2em; margin: 0 auto;">
                                        ${element.author}
                                    </span>`,
                            语言: `<span class="overflow-omit" style="max-width: ${columnWidth[2] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                        ${element.language}
                                    </span>`,
                            出版社: `<span class="overflow-omit" style="max-width: ${columnWidth[3] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                        ${element.publishingHouse}
                                    </span>`,
                            来源: `<span class="overflow-omit" style="max-width: ${columnWidth[4] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                        ${element.publishingHouse}
                                    </span>`,
                            管理: `<span class="overflow-omit" style="max-width: ${columnWidth[5] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                        <a href="<%= pageUrl %>detail?id=${element.id}">修改</a>
                                        <a href="javascript:deleteBook(${element.id});">删除</a>
                                    </span>`,
                        })
                    });

                    if (renderData.length == 0) {
                        console.log("没有搜索到相关书籍");
                        function htmlEncode(str) {
                            // refer: https://stackoverflow.com/questions/4183801/escape-html-chracters
                            var div = document.createElement('div');
                            var txt = document.createTextNode(str);
                            div.appendChild(txt);
                            return div.innerHTML;
                        }
                        if (searchText && searchText != "") {
                            //
                            renderTable({ data: `没有搜索到与 <span style="color: red;">${htmlEncode(searchText)}</span> 相关的书籍，请换个关键词再试试吧`, tableId: tableElementId, renderTableHead: true });
                        } else if (categoryId && categoryId != 0) {
                            //
                            renderTable({ data: `该分类下暂无电子书`, tableId: tableElementId, renderTableHead: true });
                        }
                    } else {
                        renderTable({ data: renderData, tableId: tableElementId, renderTableHead: true });
                    }
                } else {
                    swal(`出错啦！${data.errMsg} (错误码: ${data.errCode})`);
                }
            }).catch(function (error) {
                console.log(error);
                swal("无法连接到服务器，请检查网络连接！");
            });
    }

    function deleteBook(deleteBookId) {
        if (!confirm(`确认要删除编号为 ${deleteBookId} 的书籍吗？（关联文件不会被删除）`)) return;

        postRequest("/book/delete", { token: localStorageUtils.getToken(), id: deleteBookId })
            .then(function (responseData) {
                var axiosData = responseData.data;
                var status = axiosData.status;
                var data = axiosData.data;
                if (status === "success") {
                    console.log(data)
                    if (data == "success") {
                        search({
                            tableElementId: "book-table",
                            searchText: $("#searchInput").val(),
                            categoryId: null
                        });
                    } else {
                        swal("删除失败！");
                    }
                } else {
                    swal(`出错啦！${data.errMsg} (错误码: ${data.errCode})`);
                }
            }).catch(function (error) {
                console.log(error);
                swal("无法连接到服务器，请检查网络连接！");
            });
    }
</script>